#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstring>
#include <cassert>
#include <string>
#include <sys/stat.h>


//共享内存不随进程，随os
using namespace std;
//IPC_CREATE   IPC_EXCL
//单独使用IPC_CREATE ： 创建一个共享内存，不存在就创建，存在就直接拿着存在的返回
//IPC_EXCL不能单独使用，一般配合IPC_EXCL使用
//IPC_CREATE| IPC_EXCL： 创建一个共享内存，成功就返回，如果已经存在就失败返回

//key_t ftok(const char *pathname, int proj_id);

#define pathname "."
#define proj_id 0x454

const int gsize = 4096;

key_t getKey()
{
    key_t k = ftok(pathname, proj_id);
    if(k == -1)
    {
        cout << errno << " : " << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

string toHex(int x)
{
    char buffer[64];
    snprintf(buffer, 64, "0x%x", x);
    return buffer;
}

int createHelper(key_t k, int size, int flag)
{
    int shmid = shmget(k, size, flag);
    if(shmid == -1)
    {
        cout << errno << " : " << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}


int createShm(key_t key, int size)
{
    umask(0);
    return createHelper(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int getShm(key_t key, int size)
{
    return createHelper(key, size, IPC_CREAT);
}

//int shmctl(int shmid, int cmd, struct shmid_ds *buf);

void deleteShm(int id)
{
    int n = shmctl(id, IPC_RMID, nullptr);
    assert(n != -1);
}


char* attachShm(int id)
{
    char* start = (char*)shmat(id, nullptr, 0);
    return start;
}

char* detattachShm(char* start)
{
    int n = shmdt(start);
    assert(n != -1);
}


// enum{CLIENT = 0, SERVER};
#define CLIENT 0
#define SERVER 1


class Init
{
public:
    Init(int type) : _type(type)
    {
        key_t key = getKey(); // 获取key
        if(_type == SERVER) _shmid = createShm(key, gsize);
        else _shmid = getShm(key, gsize);
        _start = attachShm(_shmid); //绑定
    }

    char* getStart()
    {
        return _start;
    }

    ~Init()
    {
        detattachShm(_start);
        if(_type == SERVER) deleteShm(_shmid);
    }
private:
    int _type;
    int _shmid;
    char* _start;
};


















#endif



